
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.vng.zing.survey.data;

import com.vng.zing.survey.thrift.model.IDSurveyItem;
import com.vng.zing.survey.thrift.model.Error;
import java.io.IOException;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.logging.Level;
import java.util.logging.Logger;
import kyotocabinet.DB;

/**
 *
 * @author kienpd
 */
public class IDSurveyData extends Base{
    //  private static final Logger logger_ = Logger.getLogger(IDSurveyData.class);

    private static final Lock createLock_ = new ReentrantLock();
    private static IDSurveyData _instance = null;
    private static int buffer_size_profilevip = 0;
    private DB db;

    public IDSurveyData() {
        db = new DB();
        if (!db.open("database/idsurvey.kch", DB.OWRITER | DB.OCREATE)) {
            System.err.println("open error: " + db.error());
        }

    }

    public static IDSurveyData getInstance() {
        if (_instance == null) {
            createLock_.lock();
            try {
                if (_instance == null) {
                    _instance = new IDSurveyData();
                }
            } finally {
                createLock_.unlock();
            }
        }
        return _instance;
    }

    public int getMaxIDSurvey() {
        String maxId = db.get("MAX_IDSURVEY");
        if (maxId == null) {
            if (!db.set("MAX_IDSURVEY", "1")) {
                System.out.println("Database error");
                return 0;
            }
            return 1;

        }
        return Integer.parseInt(maxId);

    }

    public Error setMaxIDSurvey(int id) {
        
        if (!db.set("MAX_IDSURVEY", String.valueOf(id))) {
           return Error.ERR_SYSTEM;
        }
        return Error.SUCCESS;

    }

    public IDSurveyItem getIDSurveyItem(int idUser) {
        try {
            byte[] key =serialize(idUser);
            byte[] value = db.get(key);
           if(value == null){
             return null;
           
           }
           IDSurveyItem dSurveyItem = new IDSurveyItem();
           dSurveyItem = (IDSurveyItem) deserialize(value);
           return dSurveyItem;
        } catch (Exception ex) {
            Logger.getLogger(IDSurveyData.class.getName()).log(Level.SEVERE, null, ex);
        }
      return null;

    }

    public Error  setIDSurveyItem(int idUser, IDSurveyItem iDSurveyItem) {
      
        try {
            byte[]   key = serialize(idUser);
           byte[]  value =serialize(iDSurveyItem);
            if(!db.set(key, value)){
                return Error.ERR_SYSTEM;
            
            }
            return Error.SUCCESS;
        } catch (IOException ex) {
            Logger.getLogger(IDSurveyData.class.getName()).log(Level.SEVERE, null, ex);
        }
              return Error.ERR_SYSTEM;
    }

  
}
